<template>
	<div>
		<ProTable
			ref="table"
			:searchConfig="{
				labelWidth: '60px',
			}"
			:toolbarConfig="toolbarConfig"
			:columns="columns"
			:request="getTableData"
			:buttons="buttons"
			border
			height="100%"
		>
			<template #age="{ searchParam }">
				<div style="display: flex" v-if="searchParam">
					<el-input v-model="searchParam.minAge" placeholder="最小年龄" style="width: 50%" />
					<span class="mr10 ml10">-</span>
					<el-input v-model="searchParam.maxAge" placeholder="最大年龄" style="width: 50%" />
				</div>
			</template>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="{ selectedIds }">
				<el-button type="primary" @click="showDialog()">新增用户</el-button>
				<el-button
					type="danger"
					plain
					:disabled="!selectedIds.length"
					@click="handleDelete(selectedIds)"
				>
					批量删除用户
				</el-button>
			</template>

			<template #expand="scope">
				{{ scope.row }}
			</template>
			<template #status="{ row }">
				<el-tag :type="row.status ? 'success' : 'danger'">{{
					row.status ? "启用" : "禁用"
				}}</el-tag>
			</template>
		</ProTable>

		<BaseDialog width="50%" :visible="visible" :title="title" @cancel="handleClose" @ok="onSubmit">
			<BaseForm ref="formRef" label-width="80px" :form-list="formList" :formData="formData">
			</BaseForm>
		</BaseDialog>
	</div>
</template>

<script>
import { getUserList, addUser, updateUser, deleteUser } from "@/api/user.js";
import { getDictByType } from "@/api/dict.js";

export default {
	props: {
		path: {
			type: String,
			default: "",
		},
	},
	data() {
		return {
			toolbarConfig: {
				import: true,
				export: true,
				refresh: true,
				setCol: true,
			},
			columns: [
				{ type: "selection", fixed: "left" },
				{ type: "index", label: "#" },
				{ type: "expand", label: "Expand", width: 80 },
				{
					prop: "username",
					label: "用户姓名",
					search: { valueType: "input" },
				},
				{
					prop: "gender",
					label: "性别",
					// 字典数据
					options: [
						{
							label: "女",
							value: 1,
						},
						{
							label: "男",
							value: 2,
						},
					],
					search: {
						valueType: "select",
					},
				},
				{
					prop: "age",
					label: "年龄",
					customRender: row => row.user.detail?.age,
					search: {
						// 自定义 search 显示内容
						valueType: "custom",
					},
				},
				{
					prop: "idCard",
					label: "身份证号",
					search: { valueType: "input" },
				},
				{
					prop: "email",
					label: "邮箱",
				},
				{
					prop: "address",
					label: "居住地址",
				},
				{
					prop: "status",
					label: "用户状态",
					options: [],
					search: {
						valueType: "select",
					},
				},
				{
					prop: "createTime",
					label: "创建时间",
					width: 180,
				},
				{
					prop: "operation",
					label: "操作",
					fixed: "right",
					width: 250,
					buttons: [
						{
							label: "查看",
							on: {
								click: this.toDetail,
							},
						},
						{
							label: "编辑",
							on: {
								click: this.showDialog,
							},
						},
						{
							label: "重置密码",
							on: {
								click: row => {
									console.log("重置密码: ", row);
								},
							},
						},
						{
							label: "删除",
							disabled: row => row.status === 1,
							on: {
								click: row => {
									this.handleDelete(row.id);
								},
							},
						},
					],
				},
			],
			// 弹窗属性
			visible: false,
			title: "",
			formList: [
				{
					label: "用户姓名",
					key: "username",
					valueType: "input",
					rules: [{ required: true, message: "请输入", trigger: "blur" }],
				},
				{
					options: [
						{ label: "女", value: 1 },
						{ label: "男", value: 2 },
					],
					label: "性别",
					key: "gender",
					valueType: "select",
					rules: [{ required: true, message: "请选择", trigger: "change" }],
				},
				{
					label: "年龄",
					key: "age",
					valueType: "input-number",
					rules: [{ required: true, message: "请输入", trigger: "blur" }],
				},
				{
					label: "身份证号",
					key: "idCard",
					valueType: "input",
				},
				{
					label: "邮箱",
					key: "email",
					valueType: "input",
				},
				{
					label: "居住地址",
					key: "address",
					valueType: "input",
				},
				{
					options: [],
					label: "用户状态",
					key: "status",
					valueType: "select",
					rules: [{ required: true, message: "请选择", trigger: "change" }],
				},
				{
					label: "联动下拉",
					valueType: "select",
					key: "nextSelect",
					options: [],
					fieldProps: {
						disabled: false,
					},
					hidden: false,
				},
			],
			formData: {},
		};
	},
	watch: {
		"formData.status"(value) {
			this.handleStatusChange(value);
		},
	},
	created() {
		this.init();
	},
	methods: {
		getTableData(params) {
			return getUserList(params).then(res => res.data);
		},
		init() {
			getDictByType("user_status").then(res => {
				const arr = res.data;
				this.columns.find(item => item.prop === "status").options = arr.slice(0, 2);

				this.formList.find(item => item.key === "status").options = arr;
			});
		},
		handleStatusChange(value) {
			const target = this.formList.find(item => item.key === "nextSelect");
			switch (value) {
				case 0:
					target.hidden = false;
					target.fieldProps.disabled = false;
					target.options = [{ label: "禁用", value: 0 }];
					this.formData.nextSelect = "";
					break;
				case 1:
					target.hidden = false;
					target.fieldProps.disabled = false;
					target.options = [{ label: "启用", value: 1 }];
					this.formData.nextSelect = "";
					break;
				case 2:
					target.hidden = false;
					target.fieldProps.disabled = true;
					break;
				case 3:
					target.hidden = true;
					break;
				default:
					target.hidden = false;
					target.fieldProps.disabled = false;
					target.options = [];
					this.formData.nextSelect = "";
					break;
			}
		},
		toDetail(row) {
			if (!this.path) {
				this.$router.push(`/plugin/table/detail?id=${row.id}`);
			} else {
				this.$router.push(`${this.path}/detail?id=${row.id}`);
			}
		},
		showDialog(row) {
			if (!row) {
				this.title = "添加";
			} else {
				this.title = "编辑";
				const { age } = row.user.detail;
				this.formData = { ...row, age };
				console.log("this.formData: ", this.formData);
			}
			this.visible = true;
		},
		async onSubmit() {
			this.$refs.formRef.validate(async valid => {
				if (valid) {
					const func = this.title === "添加" ? addUser : updateUser;
					const { age, user, ...rest } = this.formData;
					const params = {
						...rest,
						age,
					};
					const res = await func(params);
					if (res) {
						this.handleClose();
						this.$refs.table.refresh();
					}
				}
			});
		},
		// 弹窗关闭事件
		handleClose() {
			this.visible = false;
			this.$refs.formRef.resetFields();
			this.formData = Object.assign({}, this.$options.data().formData);
		},
		handleDelete(value) {
			console.log("删除: ", value);
			this.$confirm("确定删除所选项吗？", "提示")
				.then(async () => {
					const id = Array.isArray(value) ? value.join(",") : value;
					const params = {
						value: id,
					};
					const res = await deleteUser(params);
					console.log("res: ", res);
				})
				.catch(err => {
					console.log("err: ", err);
				});
		},
	},
};
</script>

<style lang="scss" scoped></style>
